/**   
 * Copyright 2011 COMERE Harold
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package etrl.geometry;

import java.util.Comparator;

import etrl.geometry.LineSegmentIntersector.Intersection;
import etrl.vecmath.Vector4f;

/**
 * \class IntersectionDistanceComparator
 * \brief Class used to sort intersections found with the LineSegmentIntersector
 * @author harold
 *
 */
public class IntersectionDistanceComparator implements Comparator <LineSegmentIntersector.Intersection>
{
	/**
	 * Reference point to compute distances
	 */
	private Vector4f _point;
	
	/**
	 * Comparaison way, if false i1 < i2 means that i1 is nearest than i2 from ref point, else it is the inverse
	 */
	private boolean _inverse;
	
	/**
	 * Epsilon value to deal with double comparaison
	 */
	private final double EPSILON = 0.0001;
	
	/**
	 * \brief Initializes the comparator
	 * @param[in] point Reference point
	 * @param[in] inverse If false, the comparator will sort in ascending order, if true in descending order
	 */
	public IntersectionDistanceComparator(Vector4f point, boolean inverse)
	{
		_point = new Vector4f(point);
		_inverse = inverse;
	}
	
	/**
	 * {@inheritDoc}
	 */
	public int compare(Intersection o1, Intersection o2)
	{
		Vector4f p1 = new Vector4f(_point);
		p1.sub(o1._worldIntersectionPoint);
		double dist1 = p1.lengthSquared();
		
		Vector4f p2 = new Vector4f(_point);
		p2.sub(o2._worldIntersectionPoint);
		double dist2 = p2.lengthSquared();
		
		if(! _inverse)
			return dist1 < dist2 - EPSILON ? -1 : (dist1 > dist2 + EPSILON ? 1 : 0);
		else
			return dist1 < dist2 - EPSILON ? 1 : (dist1 > dist2 + EPSILON ? -1 : 0);			
	}

}
